#include "node.h"

#include <QDebug>

Node::Node()
    : CircuitElement(0)
{

}

void Node::onReceiveSignal(const Pin *pin, signed char signal)
{
    for(int i = 0; i < pins.count(); i++)
    {
        if (pins.at(i) != pin)
        {
            pins[i]->send(signal);
        }
    }
}

Pin* Node::createSpecialPIN()
{
    Pin* pin = CircuitElement::createSpecialPIN();
    connect(pin, SIGNAL(OnReceive(const Pin*,signed char)),this,
            SLOT(onReceiveSignal(const Pin*,signed char)));
    return pin;
}

void Node::addWire(Pin* pin)
{
    if (pin != NULL)
    {
       Pin* a = this->createSpecialPIN();
       pins.append(pin);
       Pin::unite(a, pin);
    }
}

void Node::refresh()
{
    CircuitElement::refresh();
    clearUnusedPINs();
}

void Node::clearUnusedPINs()
{
    for(int i = pins.count() - 1; i >=0; i--)
    {
        if(pins[i]->friendPIN == NULL)
        {
            Pin* p = pins.at(i);
            delete p;
            pins.remove(i);
        }
    }
}
